package com.hn658.user.core.dao.db.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.Validate;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Repository;

import com.hn658.framework.dataaccess.mybatis.AbstractMyBatisDAO;
import com.hn658.framework.dataaccess.pagination.GenericPage;
import com.hn658.user.common.entity.UserInfoEO;
import com.hn658.user.core.dao.db.IUserInfoDBDAO;

@Repository
public class UserInfoDBDAOImpl extends AbstractMyBatisDAO<UserInfoEO, Long> implements IUserInfoDBDAO{

	@Override
	public List<Long> selectUserIdByFunctionId(Long FunctionId) {
		return getSqlSession().selectList(this.getMapperNamespace()+".selectUserIdByFunctionId",FunctionId);
	}
	
	@Override
	public List<Long> selectUserIdByRoleId(Long roleId) {
		return getSqlSession().selectList(this.getMapperNamespace()+".selectUserIdByRoleId",roleId);
	}

	@Override
	public GenericPage<UserInfoEO> selectAppUser(
			Map<String, Object> queryParam, int pageSize, int startIndex,
			String orderBy, boolean isAsc) {

		// 检查参数是否为null或者元素长度为0
		// 如果是抛出异常
		Validate.notBlank(orderBy);

		// 检查分页参数
		if (pageSize < 1) {
			throw new IllegalArgumentException("分页pageSize参数必须大于1");
		}

		if (startIndex < 0) {
			throw new IllegalArgumentException("分页startIndex参数必须大于0");
		}

		if (null == queryParam) {
			queryParam = new HashMap<String, Object>();
		}
		queryParam.put("ORDERBY", orderBy);
		if (isAsc) {
			queryParam.put("ORDER", "ASC");
		} else {
			queryParam.put("ORDER", "DESC");
		}

		int totalSize = countAppUser(queryParam);

		// 如果数据Count为0，则直接返回
		if (totalSize == 0) {
			return new GenericPage<UserInfoEO>(startIndex, totalSize, pageSize,
					null);
		}

		List<UserInfoEO> pagedData = this.getSqlSession().selectList(
				this.mapperNamespace + ".selectAppUser", queryParam,
				new RowBounds(startIndex, pageSize));

		return new GenericPage<UserInfoEO>(startIndex, totalSize, pageSize,
				pagedData);
	}
	
	private int countAppUser(Map<String, Object> queryParam) {
		// 检查参数是否为null或者元素长度为0
		// 如果是抛出异常
		Validate.notEmpty(queryParam);
		
		return (Integer)this.getSqlSession().selectOne(this.mapperNamespace + ".countAppUser", queryParam);
	}
	
}
